<template>
  <div class="chat-container">
    <!-- 聊天框 -->
    <div class="chat-box">
      <div v-for="(message, index) in messages" :key="index" class="message">
        <span v-if="message.type === 'text'">{{ message.content }}</span>
        <img v-if="message.type === 'image'" :src="message.content" alt="uploaded image" class="uploaded-image" />
      </div>
    </div>

    <!-- 输入框和图标 -->
    <div class="input-area">
      <input v-model="messageInput" type="text" placeholder="Type a message..." class="message-input" />
      
      <!-- 上传图片的 Icon 按钮 -->
      <label for="image-upload" class="upload-icon">
         <van-icon name="photo" class="photo-icon" @click="btn" />
      </label>
      <input 
        id="image-upload" 
        type="file" 
        accept="image/*" 
        ref="fileInput" 
        class="image-upload" 
        @change="handleImageUpload" 
        hidden 
      />
      
      <!-- 发送按钮 -->
      <button @click="sendMessage">Send</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 聊天框消息
const messages = ref([])
// 输入框的消息内容
const messageInput = ref('')
// 选择的图片文件
const imageUrl = ref('')

// 处理图片上传
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file && file.type.startsWith('image/')) {
    const reader = new FileReader()
    reader.onload = () => {
      imageUrl.value = reader.result // 设置图片的 Data URL
    }
    reader.readAsDataURL(file)
  }
}

// 发送消息（文本或图片）
const sendMessage = () => {
  if (messageInput.value.trim() !== '') {
    messages.value.push({
      type: 'text',
      content: messageInput.value
    })
    messageInput.value = ''
  }

  // 如果选择了图片，发送图片
  if (imageUrl.value) {
    messages.value.push({
      type: 'image',
      content: imageUrl.value
    })
    imageUrl.value = '' // 清空图片数据
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  border: 1px solid #ccc;
  padding: 10px;
}

.chat-box {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.message {
  margin-bottom: 10px;
}

.uploaded-image {
  max-width: 100px;
  max-height: 100px;
}

.input-area {
  display: flex;
  align-items: center;
}

.message-input {
  flex-grow: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

.upload-icon {
  cursor: pointer;
}

button {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
}
</style>
></span></div></div></div></template>